import pRight from '@/images/common/rightGray.png';
import pArrow from '@/mainSubPack/images/shopPay/down-arrow.png';
import pTip from '@/mainSubPack/images/shopPay/tip.png';
import PointSelect from '@/components/PointSelect/index';
import { debounce } from '@/utils/helper';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import utils from '@/utils/index';
import { Button, Image, Input, Text, View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import React, { useCallback, useEffect, useReducer, useState } from 'react';
import { connect } from 'react-redux';
import GetOpenId from '@/components/GetOpenId/';
import { shopPay } from '../../utils/pay';
import './index.scss';
import PointRule from './pointRule';

const MAX_PAY_PRICE = 2000;

const ShopPayPage = ({ dispatch, loading, giftCardSelected, point }) => {
  useShowLoading(loading, ['order/payBill', 'order/getOrderPoint']);

  // 消费备注
  const [customerRemark, setCustomerRemark] = useState('');

  // 积分选择界面
  const [pointSelectIsOpened, setPointSelectIsOpen] = useState(false);
  // 积分选择结果
  const [selectedPoint, setSelectedPoint] = useState(undefined);

  // 积分介绍界面
  const [pointRuleIsOpened, setPointRuleIsOpened] = useState(false);

  const reducerf = (state, action) => {
    return { inputNum: action.inputNum, v: state.v + 1 };
  };
  const [sta, disp] = useReducer(reducerf, { inputNum: '', v: 0 });
  const [totalPayNum, setTotalPayNum] = useState(null);
  const router = useRouter();
  const { params = {} } = router;
  const merchantId = params.merchantId;
  const orgId = params.orgId;
  const orgName = decodeURIComponent(params.orgName || '');
  const [focus, setFocus] = useState(true);

  // 输入金额, 单位 分
  const inputCent = parseFloat(totalPayNum) * 100;

  // 提货券全部金额
  const giftCardFullCent = giftCardSelected.reduce((pre, cur) => cur.balance * 100 + pre, 0);

  // 积分折扣
  const pointCent = parseFloat(selectedPoint?.choosePrice ?? 0) * 100;

  // 支付金额
  let tempCent = inputCent - pointCent;

  // 提货券最大优惠
  const giftCardCent = tempCent < giftCardFullCent ? tempCent : giftCardFullCent;
  const giftCardPrice = giftCardCent / 100;

  // 真实付款价格
  const realPrice = ((inputCent - pointCent - giftCardCent) / 100).toFixed(2);

  const checkNum = (e) => {
    let value = e.detail.value;
    value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
    value = value.replace(/^(-)*(\d*)\.(\d\d).*$/, '$1$2.$3');
    if (/^\d+\.?\d{0,2}$/.test(value) === false) {
      value = e.detail.value.substring(0, e.detail.value.length - 1);
    }
    disp({ inputNum: value });

    const realPay = parseFloat(value);
    if (realPay) {
      setTotalPayNum(realPay);
    } else {
      setTotalPayNum(null);
    }
  };

  const handleNum = () => {
    if (sta.inputNum.length > 0) {
      setTotalPayNum(parseFloat(sta.inputNum));
    }
  };

  const goShopPayResult = (orderId) => {
    let url = '/mainSubPack/shopPayResult/index?orderId=' + orderId;
    Taro.navigateTo({
      url,
    });
  };

  const refreshGiftCard = useCallback(() => {
    if (!orgId) {
      return;
    }

    dispatch({
      type: 'fineCard/fineCardGetCardList',
      payload: {
        status: 1,
        storeId: orgId,
        cardIds: giftCardSelected?.map(({ id }) => {
          return id;
        }),
      },
    }).then((res) => {
      const arr = res.filter((v) => Object.keys(v).length > 0);

      // 设置是否存在可用券
      setIsExistsGiftCard(!!arr.length);

      // 设置选中的券
      return dispatch({
        type: 'productCar/setGiftCardSelect',
        payload: arr.filter(({ status }) => {
          return status === 1;
        }),
      });
    });
  }, [orgId]);

  const clear = () => {
    // 重新获取提货券
    refreshGiftCard();

    // 输入的支付金额清空
    disp({ inputNum: '' });
    setTotalPayNum(null);

    // 重新获取积分
    dispatch({
      type: 'order/getOrderPoint',
      payload: {
        simplePrice: [0],
        sumPrice: 0,
      },
    });

    // 备注清空
    setCustomerRemark('');
  };

  const handleShopPay = debounce(() => {
    setFocus(false);

    if (sta.inputNum.length == 0 || totalPayNum === null) {
      Taro.showToast({
        title: '请输入消费金额',
        duration: 1000,
        icon: 'none',
      });
      return;
    }

    if (parseFloat(realPrice) > MAX_PAY_PRICE) {
      Taro.showModal({
        title: '买单提示',
        content: `单笔消费的实付金额不得超过${MAX_PAY_PRICE}元`,
        confirmText: '修改金额',
        showCancel: false,
        complete: () => {
          setFocus(true);
        },
      });

      return;
    }

    Taro.showModal({
      title: '买单提示',
      content: '请到店后与服务员确认金额再付款',
      showCancel: true,
      cancelColor: '#000000',
      confirmColor: '#576B95',
      success: function (res) {
        if (res.confirm) {
          handlePay();
        }
      },
    });
  }, 2000);

  const fail = (txt = '支付失败', orderId) => {
    return Taro.showModal({
      title: '买单提示',
      content: txt,
      confirmColor: '#576B95',
      complete: () => {
        if (!orderId) {
          return;
        }

        Taro.navigateTo({
          url: `/orderSubPack/orderDetail/index?orderId=${orderId}`,
        });
      },
    });
  };

  const handlePay = async () => {
    return shopPay(dispatch, {
      merchantId,
      orgId,
      orgName,
      totalPayment: realPrice,
      totalPrice: sta.inputNum,
      giftCardIdList: giftCardSelected?.map((v) => v.id),
      customerRemark,
      pointsList: selectedPoint?.chooseDeductionList,
    })
      .then(({ orderId }) => {
        goShopPayResult(orderId);

        clear();
      })
      .catch((e) => {
        const { orderId, txt } = e?.extra ?? {};

        fail(txt, orderId);

        clear();
      });
  };

  // 获取总积分, 用于第一次选择
  useEffect(() => {
    dispatch({
      type: 'order/getOrderPoint',
      payload: {
        simplePrice: [0],
        sumPrice: 0,
      },
    });
  }, []);

  // 获取可用积分, 用于选择使用的积分
  useEffect(() => {
    if (!pointSelectIsOpened) {
      return;
    }

    const v = parseFloat(totalPayNum);

    if (!v) {
      return;
    }

    dispatch({
      type: 'order/getOrderPoint',
      payload: {
        simplePrice: [v],
        sumPrice: v,
      },
    });
  }, [pointSelectIsOpened]);

  // 清除选择的积分
  useEffect(() => {
    setSelectedPoint(undefined);
  }, [totalPayNum]);

  const [isExistsGiftCard, setIsExistsGiftCard] = useState(undefined);
  // 获取提货券状态
  useEffect(refreshGiftCard, [orgId]);

  const getGiftCardStatus = useCallback(() => {
    // 提货券还在获取阶段
    if (isExistsGiftCard === undefined) {
      return null;
    }

    // 没有提货券
    if (isExistsGiftCard === false) {
      return <View className="txt inactive">无可用券</View>;
    }

    // 有提货券, 但是没有输入支付金额
    // 有支付金额, 没选择券
    if (!totalPayNum || (totalPayNum && !giftCardSelected.length)) {
      return (
        <>
          <View className="txt customePageStyle">有可用券</View>
          <Image src={pRight} className="right-img black" />
        </>
      );
    }

    // 选择了提货券, 有支付金额
    return <View className="txt">- ¥ {parseFloat(giftCardPrice).toFixed(2)}</View>;
  }, [isExistsGiftCard, totalPayNum, giftCardPrice]);

  return (
    <View
      className="shopPay"
      style={{
        height: utils.getCalcHeight({}, 8),
      }}
    >
      <GetOpenId />

      <PointRule
        isOpened={pointRuleIsOpened}
        onClose={() => {
          setPointRuleIsOpened(false);
        }}
      />
      <PointSelect
        point={point}
        isOpened={pointSelectIsOpened}
        isShowNonuse
        selectedPoint={selectedPoint}
        onSelect={(v) => {
          setSelectedPoint(v);
          setPointSelectIsOpen(false);
        }}
        onClose={() => {
          setPointSelectIsOpen(false);
        }}
      ></PointSelect>

      {realPrice > 2000 ? (
        <View className="notice">
          <View className="txt">单笔消费不可超过2000元</View>
        </View>
      ) : null}

      <View className="name">{orgName}</View>
      <View className="item">
        <Text className="lable">消费金额：</Text>
        <Input
          className="val inputValue"
          type="digit"
          maxlength="10"
          value={sta.inputNum}
          onInput={checkNum}
          onBlur={handleNum}
          placeholder="询问服务员后输入"
          placeholderClass="pld"
          focus={focus}
        />
      </View>

      <View className="multi-item">
        <View className="line">
          <View
            className="label"
            onClick={() => {
              setPointRuleIsOpened(true);
            }}
          >
            <Text className="txt">积分</Text>
            <Image src={pTip} className="tip" />
          </View>
          <View
            className="point"
            onClick={() => {
              if (!parseFloat(totalPayNum)) {
                Taro.showToast({
                  title: '请先输入消费金额',
                  icon: 'none',
                  duration: 2000,
                });

                return;
              }

              setPointSelectIsOpen(true);
            }}
          >
            <Text>
              {selectedPoint
                ? `可用${selectedPoint.choosePoint}积分抵用${selectedPoint.choosePrice}元`
                : `共${point?.sumPoint ?? 0}积分可用`}
            </Text>
            <Image src={pArrow} className="arrow" />
          </View>
        </View>

        <View className="split-line"></View>

        <View
          className="line"
          onClick={() => {
            setFocus(false);

            Taro.navigateTo({
              url: '/giftCardSubPack/giftCardSelect/index?orgId=' + orgId,
            });
          }}
        >
          <View className="label">
            <View className="txt">提货券：</View>
          </View>
          <View className="gift-card">{getGiftCardStatus()}</View>
        </View>
      </View>

      <View className="item">
        <Text className="lable">实付金额：</Text>
        <Text className="val numValue">{totalPayNum !== null ? '￥' + realPrice : ''}</Text>
      </View>

      <View className="item">
        <Text className="lable">备注：</Text>
        <Input
          className="val inputValue"
          type="string"
          value={customerRemark}
          onInput={(v) => {
            setCustomerRemark(v.detail.value);
          }}
          placeholder="记录此次消费的备注"
          placeholderClass="pld"
        />
      </View>

      <Button
        className={[
          'btn-red upDis customePageBackgroundStyle',
          totalPayNum === null && 'disable',
        ].join(' ')}
        onClick={handleShopPay}
      >
        确认买单
      </Button>
    </View>
  );
};

export default connect(({ loading, productCar, order }) => ({
  loading,
  giftCardSelected: productCar.giftCardSelected,
  point: order.point,
}))(ShopPayPage);
